package com.sinosoft.attachment;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.sinosoft.base.GenericDaoHibernate;
import com.sinosoft.util.CheckEmpty;
@Repository
public class AttachmentDaoHibernate extends GenericDaoHibernate<Attachment, Long>
		implements AttachmentDao {
	
	public AttachmentDaoHibernate(){
		super(Attachment.class);
	}

	/**
	 * 获取资源列表
	 */
    public List<Attachment> getAttachments(Attachment ach,int index,int pagesize){
    	Session session=null;
    	List<Attachment> list=null;
    	try {
			session=getHibernateTemplate().getSessionFactory().openSession();
			Criteria c=session.createCriteria(Attachment.class);
			if(null!=ach){
				if(!CheckEmpty.isEmpty(ach.getFileName())){
					c.add(Restrictions.like("fileName", "%"+ach.getFileName()+"%"));
				}
				if(null!=ach.getFileType()&&ach.getFileType()>0){
					c.add(Restrictions.eq("fileType", ach.getFileType()));
				}
				if(null!=ach.getIsRelease()&&ach.getIsRelease()>0){
					c.add(Restrictions.eq("isRelease", ach.getIsRelease()));
				}
			}
			if(index>=0&&pagesize>0){
				c.setFirstResult(index);
				c.setMaxResults(pagesize);
			}
			c.addOrder(Order.desc("id"));
			list=c.list();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
    	return list;
    }
	
    /**
	 * 保存资源信息
	 */
	public void saveAttachment(Attachment am){
        try {
			getHibernateTemplate().saveOrUpdate(am);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public int getAttachment(String sql){
		int result=0;
		Session session=null;
		try {
			if(!CheckEmpty.isEmpty(sql)){
				session=getHibernateTemplate().getSessionFactory().openSession();
				Query query=session.createQuery(sql);
				result=Integer.parseInt(query.list().get(0).toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return result;
	}
	
	/**
	 * 根据资源id获取资源信息
	 */
	public Attachment getAttachmentById(Long achid){
		try {
			List<Attachment> list=getHibernateTemplate().find("from Attachment where id=?",achid);
			if(null!=list&&list.size()>0){
				return list.get(0);
			}
		} catch (Exception e) {
			
		}
		return null;
	}
	
	/**
	 * 删除资源
	 */
	public void deleteAttachment(Attachment ach){
		try {
			getHibernateTemplate().delete(ach);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
